<?php

/**
 * Created by JetBrains PhpStorm.
 * User: Đặng Khánh Trung
 * Date: 11/2/12
 * Time: 1:19 PM
 * To change this template use File | Settings | File Templates.
 */
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// Include dependancy of the main model form
jimport('joomla.application.component.modelform');
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
// Include dependancy of the dispatcher
jimport('joomla.event.dispatcher');

/**
 * Dienbienhocham Model
 */
class VastModelDienbienhocham extends JModelForm {

    /**
     * @var object item
     */
    protected $_item;

    /**
     * Get the dienbienhocham
     * @return object The dienbienhocham to be displayed to the user
     */
    function getItem() {

        if (!isset($this->_item)) {
            $id = JRequest::getInt('did');
            
            $db = JFactory::getDBO();
            $query = $db->getQuery(true);

            $query->select('a.*, b.mota, b.thutu');
            $query->from('#__dienbienhocham AS a');
            $query->join('INNER', '#__hocham AS b ON a.hocham_id = b.id');
            $query->where('a.id = ' . $id);

            $db->setQuery($query);
            $dienbienhocham = $db->loadObject();
            
            $this->_item = array();
            foreach ($dienbienhocham as $key => $value) {
                $this->_item[$key] = $value;
            }            
            
        }
        
        return $this->_item;
    }

    public function updateItem($data) {
        $id = JRequest::getInt('did');
        
        // set the data into a query to update the record
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->clear();
        $query->update('#__dienbienhocham');
        
        foreach($data as $key => $value) {
            if (is_numeric($value)) {
                $query->set($key . ' = ' . $value);
            } else {
                $query->set($key . ' = ' . $db->quote($value));
            }
        }
        
        $query->where('id = ' . $id);
        
        $db->setQuery($query);
                        
        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        } else {
            $query = $db->getQuery(true);
            $query->select('a.*, b.*');
            $query->from('#__dienbienhocham AS a');
            $query->where('a.hosocanbo_id = ' . $data['hosocanbo_id']);
            $query->join('INNER', '#__hocham AS b ON a.hocham_id = b.id');
            $query->order('b.thutu ASC');
            $query->where('a.hocham_id != ' . $data['hocham_id']);
            
            $db->setQuery($query);
            $canbo = $db->loadObject();
                                        
            $query = $db->getQuery(true);
            $query->select('a.*');
            $query->from('#__hocham AS a');
            $query->where('a.id = ' . $data['hocham_id']);
            
            $db->setQuery($query);
            $hocham = $db->loadObject();
                        
            if ((isset($canbo) && $hocham->thutu < $canbo->thutu) || !isset($canbo) || $canbo === NULL)
            {
                $query = $db->getQuery(true);
                $query->update('#__hosocanbo');
                $query->set('`hocham_id` = ' . $hocham->id);
                $query->where('`id` = ' . (int)$data['hosocanbo_id']);
                $db->setQuery($query);
                                
                if (!$db->query()) {
                    JError::raiseError(500, $db->getErrorMsg());
                    return false;
                }
                            
            }    
            
            $query = $db->getQuery(true);
            $query->clear();
            
            $query->select('a.*');
            $query->from('#__hosocanbo AS a');
            $query->where('a.id = ' . $data['hosocanbo_id']);
            
            $db->setQuery($query);
            $canbo = $db->loadObject();
                        
            JVastLog::addLog(date('Y-m-d'), $_SERVER['REMOTE_ADDR'], 'Cập nhật thông tin học hàm của cán bộ ' . $canbo->hoten, JFactory::getUser()->id, VastHelper::getHosocanbo()->id);

            return true;
        }
    }

    public function deleteItem($did)
    {        
        // set the data into a query to update the record
        $db = $this->getDbo();

        $query = 'DELETE FROM #__dienbienhocham WHERE `id` = ' . (int)$did;
                
        $db->setQuery($query);
        
        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        } else {
            $query = $db->getQuery(true);
            
            $query->select('a.*, b.thutu');
            $query->from('#__dienbienhocham AS a');
            $query->join('INNER', '#__hocham AS b ON b.id = a.hocham_id');    
            $query->order('b.thutu ASC');
            $query->where('a.id != ' . $did);
            
            $db->setQuery($query);
            
            $hocham = $db->loadObject();
                                    
            if (!isset($hocham)) 
            {
                $query = 'UPDATE #__hosocanbo SET `hocham_id` = NULL WHERE `id` = ' . $hocham->hosocanbo_id;                
            }   
            else
            {
                $query = 'UPDATE #__hosocanbo SET `hocham_id` = ' . $hocham->hocham_id . ' WHERE `id` = ' . $hocham->hosocanbo_id;          
            } 
            
            $db->setQuery($query);
            
            if (!$db->query()) {
                JError::raiseError(500, $db->getErrorMsg());
                return false;
            }

            $query = $db->getQuery(true);
            $query->clear();
            
            $query->select('a.*');
            $query->from('#__hosocanbo AS a');
            $query->join('INNER', '#__dienbienhocham AS b ON b.hosocanbo_id = a.id');
            $query->where('b.id = ' . $did);
            
            $db->setQuery($query);
            $canbo = $db->loadObject();
            
            JVastLog::addLog(date('Y-m-d'), $_SERVER['REMOTE_ADDR'], 'Xóa thông tin học hàm của cán bộ ' . $canbo->hoten, JFactory::getUser()->id, VastHelper::getHosocanbo()->id);
            
            return true;
        }        
    }

    public function getForm($data = array(), $loadData = true) {
        // Get the form.
        $form = $this->loadForm('com_vast.dienbienhocham', 'dienbienhocham', array('control' => 'jform', 'load_data' => true));
        if (empty($form)) {
            return false;
        }
        $jinput = JFactory::getApplication()->input;

        // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first.
        if ($jinput->get('a_id')) {
            $id = $jinput->get('a_id', 0);
        }
        // The back end uses id so we use that the rest of the time and set it to 0 by default.
        else {
            $id = $jinput->get('id', 0);
        }

        return $form;
    }

    /**
     * Method to get the data that should be injected in the form.
     *
     * @return	mixed	The data for the form.
     * @since	1.6
     */
    protected function loadFormData() {
        // Check the session for previously entered form data.

        $data = $this->getItem();

        return $data;
    }

    /**
     * Get the hosocanbo
     * @return string The message to be displayed to the user
     */
    public function getCanbo()
    {
        $id = JRequest::getInt('id');

        $db = JFactory::getDBO();
        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__hosocanbo AS a');
        $query->where('a.id = ' . $id);

        $db->setQuery($query);
        $canbo = $db->loadObject();
        return $canbo;
    }  
    
    /**
     * Get the message
     * @return string The message to be displayed to the user
     */
    public function getPhong()
    {
        $id = JRequest::getInt('id');

        $db = JFactory::getDBO();
        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__phong AS a');
        $query->join('INNER', '#__congtac AS b ON b.phong_id = a.id');
        $query->where('b.hosocanbo_id = ' . $id);
        $query->where('b.taivi = 1');
        
        $db->setQuery($query);
        $phong = $db->loadObject();
        
        return $phong;
    }

    public function getKhoi() 
    {
        $db = JFactory::getDBO();
        $query = $db->getQuery(true);
        $donvi = $this->getDonvi();
        $phong = $this->getPhong();
        if ($donvi !== NULL)
        {
            $query->select('a.*');
            $query->from('#__khoi AS a');
            $query->where('a.id = ' . $donvi->khoi_id);
            $db->setQuery($query);
            
            return $db->loadObject();            
        }
        elseif ($phong !== NULL)
        {
            $query->select('a.*');
            $query->from('#__donvi AS a');
            $query->where('a.id = ' . $phong->donvi_id);
            $db->setQuery($query);            
            
            $tmp = $db->loadObject();
            if ($tmp !== NULL)
            {
                $query->select('a.*');
                $query->from('#__khoi AS a');
                $query->where('a.id = ' . $tmp->khoi_id);
                $db->setQuery($query);
                
                return $db->loadObject();                            
            }
        }
        
        return NULL;
    }
        
    public function getDonvi() {
        $id = JRequest::getInt('id');
      
        $db = JFactory::getDBO();
        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__donvi AS a');
        $query->join('INNER', '#__congtac AS b ON b.donvi_id = a.id');
        $query->where('b.hosocanbo_id = ' . $id);
        $query->where('b.taivi = 1');
        $db->setQuery($query);
        return $db->loadObject();

    }      
    
}